package com.gitee.limaozhi.nio.example01;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @author hzlimaozhi
 * @date 2019/12/20 10:48
 */
public class Buffer {

    public static void main(String[] args) throws IOException {
        String inFile = "D:\\Phoenix\\Java\\Code\\gitee.com\\limaozhi\\demo-java-net-io\\src\\main\\resources\\in.txt";
        String outFile = "D:\\Phoenix\\Java\\Code\\gitee.com\\limaozhi\\demo-java-net-io\\src\\main\\resources\\out.txt";

        // 文件通道
        FileChannel inChannel = new FileInputStream(inFile).getChannel();
        // 文件通道
        FileChannel outChannel = new FileOutputStream(outFile).getChannel();
        // 缓冲区
        ByteBuffer buffer = ByteBuffer.allocate(1024);

        // 1. buffer切换写模式
        // 2. 从inChannel读取数据写到buffer
        // 3. buffer切换读模式
        // 4. 从buffer读取数据写到outChannel

        for (int i = 1; i < Integer.MAX_VALUE; i++) {
            // 1. buffer切换写模式
            buffer.clear();

            // 2. 从inChannel读取数据写到buffer
            int read = inChannel.read(buffer);
            if (read == -1) {
                // EOF
                break;
            }
            System.out.println("第" + i + "次读取：" + read);

            // 3. buffer切换读模式
            buffer.flip();

            // 4. 从buffer读取数据写到outChannel
            int write = outChannel.write(buffer);
            System.out.println("第" + i + "次写入：" + write);

            // 强制刷新到磁盘
            outChannel.force(true);
        }

        inChannel.close();
        outChannel.close();
    }

}
